package practicalcases.auth;

import practicalcases.auth.dao.UserDaoImpl;

public class DefaultApiAuthenticator{

    private UserDaoImpl storage;

    public DefaultApiAuthenticator() {
        storage = new UserDaoImpl();
    }

    public DefaultApiAuthenticator(UserDaoImpl storage) {
        this.storage = storage;
    }

    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.buildFromUrl(url);
        auth(apiRequest);
    }

    public void auth(ApiRequest apiRequest) {
        String appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        long timestamp = apiRequest.getTimestamp();
        String originalUrl = apiRequest.getBaseUrl();

        AuthToken clientAuthToken = new AuthToken(token, timestamp);
        if (clientAuthToken.isExpired()) {
            throw new RuntimeException("Token is expired!!!");
        }
        String password = storage.getPasswordByAppId(appId);
        AuthToken serverAuthToken = AuthToken.generate(originalUrl, appId, timestamp, password);
        if (!serverAuthToken.match(clientAuthToken)) {
            throw new RuntimeException("Token verification failed!!!");
        }
        System.out.println("Token verification success!");
    }

}